var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var save = require('./routes/save');
var runners=require('./routes/runners');
var compile=require('./routes/compile');
var preview=require('./routes/preview');
var read=require('./routes/read');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, '..', 'adf-all','adf.core','pub')));
app.use(express.static(path.join(__dirname, '..', 'adf-all','adf.core','agef', 'dist')));
app.use(express.static(path.join(__dirname, '..', 'adf-all','adf.bundles','pub')));
app.use(express.static(path.join(__dirname, '..', 'adf-all','bcp.bundles','pub')));
app.use(express.static(path.join(__dirname, '..', 'adf-all','bcp.attr','pub')));


app.use('/', routes);
app.use('/save',save);
app.use('/runners',runners);
app.use('/compile',compile);
app.use('/preview',preview);
app.use('/read',read);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

var spawn=require('child_process').spawn;
var child=spawn('node', ["www"],{cwd:path.join(__dirname,'..','enzyme-adf-compiler','bin')});

child.stdout.on('data', function(data) {
    console.log(data.toString());
});
child.stderr.on('data', function(data) {
    console.log(data.toString());
});
child.on('exit', function(code) {
    console.log('Child exited with code', code);
});

var fs = require( 'fs' ),
    stat = fs.stat;

/*
 * 复制目录中的所有文件包括子目录
 * @param{ String } 需要复制的目录
 * @param{ String } 复制到指定的目录
 */
var copy = function( src, dst ){
    // 读取目录中的所有文件/目录
    fs.readdir( src, function( err, paths ){
        if( err ){
            throw err;
        }
        paths.forEach(function( path ){
            var _src = src + '/' + path,
                _dst = dst + '/' + path,
                readable, writable;
            stat( _src, function( err, st ){
                if( err ){
                    throw err;
                }
                // 判断是否为文件
                if( st.isFile() ){
                    // 创建读取流
                    readable = fs.createReadStream( _src );
                    // 创建写入流
                    writable = fs.createWriteStream( _dst );
                    // 通过管道来传输流
                    readable.pipe( writable );
                }
                // 如果是目录则递归调用自身
                else if( st.isDirectory() ){
                    exists( _src, _dst, copy );
                }
            });
        });
    });
};
// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
var exists = function( src, dst, callback ){
    fs.exists( dst, function( exists ){
        // 已存在
        if( exists ){
            callback( src, dst );
        }
        // 不存在
        else{
            fs.mkdir( dst, function(){
                callback( src, dst );
            });
        }
    });
};
// 复制目录
exists( path.join(__dirname,'..','bundles'), path.join(__dirname,'..','mvc-new','bundles'), copy );

module.exports = app;
